<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑地址' : '新增地址'"
    :width="isMobile ? '90%' : '500px'"
    :top="isMobile ? '5vh' : '15vh'"
    @close="handleClose"
  >
    <el-form ref="addressFormRef" :model="addressForm" :rules="addressRules" :label-width="isMobile ? '0px' : '80px'" label-position="top" class="vertical-form">
      <el-form-item label="收货人" prop="consignee">
        <el-input v-model="addressForm.consignee" placeholder="请输入收货人姓名" class="full-width" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="addressForm.phone" placeholder="请输入手机号" class="full-width" />
      </el-form-item>

      <el-form-item label="所在地区" prop="region">
        <el-cascader
          v-model="addressForm.region"
          :options="regionOptions"
          :props="cascaderProps"
          placeholder="请选择省市区"
          class="full-width"
        />
      </el-form-item>

      <el-form-item label="详细地址" prop="address">
        <el-input
          v-model="addressForm.address"
          type="textarea"
          :rows="3"
          placeholder="请输入详细地址"
          class="full-width"
        />
      </el-form-item>

      <el-form-item label="设为默认" prop="isDefault">
        <div class="default-switch-container">
          <el-switch v-model="addressForm.isDefault" />
          <span class="switch-label">{{ addressForm.isDefault ? '是' : '否' }}</span>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { regionData } from 'element-china-area-data'
import { AddressUtils } from '@/utils/address'
import { addressService } from '@/api'
import type { Address, AddressCreateRequest, AddressUpdateRequest } from '@/types'

interface Props {
  modelValue: boolean
  address?: Address | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'addressSelected', address: Address): void
  (e: 'addressUpdated'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const addressFormRef = ref()
const loading = ref(false)
const regionOptions = ref(regionData)

// 响应式断点检测
const isMobile = ref(false)
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

const addressForm = ref({
  consignee: '',
  phone: '',
  region: [] as string[],
  address: '',
  isDefault: false,
})

const addressRules = {
  consignee: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  region: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' },
  ],
}

const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
}

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

const isEdit = computed(() => props.address !== null)

// 方法
const loadRegions = async () => {
  // 使用element-china-area-data提供的完整数据，无需异步加载
  console.log('地区数据已加载，共', regionOptions.value.length, '个省份')
}

const resetForm = () => {
  addressForm.value = {
    consignee: '',
    phone: '',
    region: [],
    address: '',
    isDefault: false,
  }
}

const setFormValues = (address: Address) => {
  addressForm.value = {
    consignee: address.recipientName,
    phone: address.phone,
    // 使用工具函数处理地区数据转换
    region: AddressUtils.addressToRegionCodes({
      province: address.province,
      city: address.city,
      district: address.district
    }),
    address: address.detailedAddress,
    isDefault: address.isDefault,
  }
}

const handleSubmit = async () => {
  if (!addressFormRef.value) return

  try {
    await addressFormRef.value.validate()
    loading.value = true

    const [province, city, district] = addressForm.value.region
    const requestData = {
      recipientName: addressForm.value.consignee,
      phone: addressForm.value.phone,
      province,
      city,
      district,
      detailedAddress: addressForm.value.address,
      isDefault: addressForm.value.isDefault,
    }

    let result
    if (isEdit.value && props.address) {
      result = await addressService.updateAddress({
        ...requestData,
        id: props.address.id,
      } as AddressUpdateRequest)
    } else {
      result = await addressService.addAddress({
        ...requestData,
        userId: 0, // 这里需要从store或props获取实际的userId
      } as AddressCreateRequest)
    }

    if (result.data && result.data.code === 200) {
      ElMessage.success(isEdit.value ? '地址更新成功' : '地址添加成功')
      emit('addressSelected', result.data.data)
      emit('addressUpdated')
      handleClose()
    } else {
      ElMessage.error(result.data?.msg || '操作失败')
    }
  } catch (error: any) {
    console.error('Failed to save address:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 监听地址变化
watch(
  () => props.address,
  (newAddress) => {
    if (newAddress) {
      setFormValues(newAddress)
    } else {
      resetForm()
    }
  },
)

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (visible) {
    loadRegions()
    if (isEdit.value && props.address) {
      setFormValues(props.address)
    } else {
      resetForm()
    }
  }
})

// 监听窗口大小变化
onMounted(() => {
  checkMobile()
  window.addEventListener('resize', checkMobile)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})
</script>

<style scoped lang="scss">
.full-width {
  width: 100%;
}

.dialog-footer {
  text-align: right;
}

.default-switch-container {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .switch-label {
    font-size: 14px;
    color: #606266;
  }
}

.vertical-form {
  :deep(.el-form-item) {
    display: block;
    margin-bottom: 20px;
  }
  
  :deep(.el-form-item__content) {
    display: block;
    width: 100%;
  }
  
  :deep(.el-form-item__label) {
    display: block;
    text-align: left;
    margin-bottom: 8px;
    font-weight: 500;
    color: #303133;
  }
}

// 移动端适配
@media (max-width: 768px) {
  :deep(.el-dialog) {
    margin: 5vh auto !important;
  }
  
  :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  .vertical-form {
    :deep(.el-form-item) {
      margin-bottom: 24px;
    }
    
    :deep(.el-form-item__label) {
      margin-bottom: 12px;
      font-size: 16px;
    }
    
    :deep(.el-form-item__content) {
      width: 100%;
    }
  }
  
  :deep(.el-input),
  :deep(.el-cascader) {
    width: 100%;
  }
  
  :deep(.el-textarea__inner) {
    min-height: 80px;
  }
  
  .default-switch-container {
    justify-content: flex-start;
    
    .switch-label {
      font-size: 14px;
      color: #606266;
    }
  }
  
  .dialog-footer {
    text-align: center;
    
    .el-button {
      width: 100%;
      margin: 5px 0;
    }
  }
}

// 桌面端优化
@media (min-width: 769px) {
  .vertical-form {
    :deep(.el-form-item) {
      margin-bottom: 28px;
    }
    
    :deep(.el-form-item__label) {
      font-weight: 600;
      color: #303133;
      margin-bottom: 10px;
      font-size: 15px;
    }
    
    :deep(.el-form-item__content) {
      width: 100%;
    }
  }
  
  :deep(.el-input),
  :deep(.el-cascader) {
    width: 100%;
  }
  
  :deep(.el-textarea__inner) {
    min-height: 80px;
  }
}
</style>
